package com.example.demo.service.impl;

import com.example.demo.mapper.MessageMapper;
import com.example.demo.myModel.entity.Message;
import com.example.demo.service.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 通知服务实现类
 */
@Service
@Slf4j
public class NotificationServiceImpl implements NotificationService {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private MessageMapper messageMapper;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    @Async("signUpTaskExecutor")
    public void sendSystemNotification(Integer userId, String message) {
        try {
            Message systemMessage = new Message();
            systemMessage.setReceiverId(userId);
            systemMessage.setTitle("系统通知");
            systemMessage.setContent(message);
            systemMessage.setType(1);
            systemMessage.setIsRead(0);
            
            messageMapper.insert(systemMessage);
            log.info("发送系统通知成功 - 用户ID: {}, 内容: {}", userId, message);
        } catch (Exception e) {
            log.error("发送系统通知失败 - 用户ID: {}", userId, e);
        }
    }

    @Override
    @Async("signUpTaskExecutor")
    public void sendEmailNotification(String email, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(email);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("发送邮件成功 - 接收者: {}, 主题: {}", email, subject);
        } catch (Exception e) {
            log.error("发送邮件失败 - 接收者: {}, 主题: {}", email, subject, e);
        }
    }
} 